#include "eeprom.h"
#include "DCM_driver.h"

#define EEPROM_UNLOCK_KEY1 0xfedcba98
#define EEPROM_UNLOCK_KEY2 0x76543210

/************************************************************
 * @brief: Initialize EEPROM module
 * @return <None>
 ************************************************************/
void EEPROM_Init(void)
{
    /*unlock sysctrl register*/
    SYSCTRL->LKKEYR = SYSCTRL_UNLOCK_KEY;

    /*enable */
    SYSCTRL->SCCR_b.AHBCEN = 1;
    SYSCTRL->SCCR_b.APBCEN = 1;
    /* ENABLE AHB EEPROM CLK */
    SYSCTRL->AHBCGR_b.EPRCEN = 1;

    /*unlock EEPROM*/
    EEPROM_CTRL->OKR = EEPROM_UNLOCK_KEY1;
    EEPROM_CTRL->OKR = EEPROM_UNLOCK_KEY2;

    /*config EEPROM*/
    EEPROM_CTRL->ECR_b.SBIE = 1;
    EEPROM_CTRL->ECR_b.DBIE = 1;
}

/************************************************************
 * @brief: EEPROM erase pages
 * @param <uint32_t> addr
 * @param <uint8_t> pages
 * @return <None>
 ************************************************************/
void EEPROM_Erase(uint32_t addr, uint8_t page)
{
    /* Check  Status of SBC */
    while (EEPROM_CTRL->FSR_b.BUSY != 0x00)
        ;
    EEPROM_CTRL->ECR_b.WLA = 1;
    *((int32_t *)(addr + 8 * page)) = 0x00;
    *((int32_t *)(addr + 8 * page + 4)) = 0x00;
    EEPROM_CTRL->ECR_b.WLA = 0;
    EEPROM_CTRL->ECR_b.ERA = 1;
    /* Check  Status of ERA */
    while (EEPROM_CTRL->ECR_b.ERA != 0x00)
        ;
}

/************************************************************
 * @brief: EEPROM write page
 * @param <uint32_t> addr
 * @param <uint8_t> page
 * @param <uint32_t> *data
 * @return <None>
 ************************************************************/
void EEPROM_Write(uint32_t addr, uint8_t page, int32_t *data)
{
    /* Check  Status of SBC */
    while (EEPROM_CTRL->FSR_b.BUSY != 0x00)
        ;
    /*data changed*/
    *((int32_t *)(addr + 8 * page)) = data[0];
    *((int32_t *)(addr + 8 * page + 4)) = data[1];
    /* Check  Status of SBC */
    while (EEPROM_CTRL->FSR_b.BUSY != 0x00)
        ;
}

/************************************************************
 * @brief: read for EEPROM data
 * @author:
 * @param <int> page read page_x data
 * @return <None>
 ************************************************************/
void EEPROM_Read_Page0(uint8_t page)
{
    u8LearnNone = *((int32_t *)(EEPROMMEM_BASE + 8 * page));
    s16PosAdcMax = *((int32_t *)(EEPROMMEM_BASE + 8 * page + 4));
}
/************************************************************
 * @brief: read for EEPROM data
 * @author:
 * @param <int> page read page_x data
 * @return <None>
 ************************************************************/
void EEPROM_Read_Page1(uint8_t page)
{
    DCMotorVar.s16AngleMax = *((int32_t *)(EEPROMMEM_BASE + 8 * page));
}
